package com.concurrent.chenjun.test.future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class CallableDemo implements Callable<String>
{
	private int i = 0;
	public CallableDemo(int i)
	{
		this.i = i;
	}
	@Override
	public String call() throws Exception
	{
		return "current Thread is :"+Thread.currentThread().getName()+"(i="+i+")";
	}
}

public class CallableAndFuture
{
	public static void main(String[] args)
	{
		ExecutorService executorService = Executors.newCachedThreadPool();
		List<Future<String>> fs = new ArrayList<Future<String>>();
		for(int i=0; i<10; i++)
		{
			Future<String> future = executorService.submit(new CallableDemo(i));
			fs.add(future);
		}
		for(Future<String> future : fs)
		{
			try
			{
				System.out.println(future.get());
			} 
			catch (InterruptedException e)
			{
				e.printStackTrace();
			} 
			catch (ExecutionException e)
			{
				e.printStackTrace();
			}
			finally
			{
				executorService.shutdown();
			}
		}
	}
}
